import {Injectable} from '@angular/core';
import {
  HttpErrorResponse,
  HttpEvent,
  HttpHandler,
  HttpInterceptor,
  HttpRequest,
  HttpResponse
} from '@angular/common/http';

import {Observable, throwError} from 'rxjs';
import {LoginAdmin} from "../api/LoginAdmin";
import {Config} from "../api/Config";
import {catchError, map} from "rxjs/operators";
import {Router} from "@angular/router";

@Injectable()
export class JWTInterceptor implements HttpInterceptor {

  constructor(private loginAdmin: LoginAdmin,
              private router: Router,
              private configManage: Config) {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (this.loginAdmin.isLogin) {
      request = request.clone({
        setHeaders: {
          'Authorization-Manage': this.loginAdmin.jwt
        }
      });

      return next.handle(request).pipe(
        map((event: HttpEvent<any>) => {
          if (event instanceof HttpResponse) {
            const jwt = event.headers.get('Authorization-Manage');
            const jwtTime = event.headers.get('Authorization-Manage-Expire');
            if (jwt) {
              this.loginAdmin.jwt = jwt;
              this.loginAdmin.jwtExpire = jwtTime;
              this.loginAdmin.save();
            }
          }
          return event;
        }),
        catchError((error: HttpErrorResponse) => {
          if (error.status === 401 || error.status === 403) {
            this.loginAdmin.clean();
            this.router.navigate([this.configManage.loginUrl], {queryParams: {msg: '没有权限访问'}});
          }
          return throwError(error);
        }));
    } else {
      return next.handle(request);
    }

  }
}
